package com.aiclient.service;

import com.aiclient.model.Chat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

public class ChatService {
    private final HttpClient client;
    private final ObjectMapper mapper;
    private final String BASE_URL = "http://localhost:8083/ai/chat";
    
    public ChatService() {
        this.client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30))
            .build();
        this.mapper = new ObjectMapper();
    }
    
    public Chat createNewChat() {
        return new Chat();
    }
    
    public void sendMessageStream(String message, String model, Consumer<String> onChunk, Runnable onComplete,Chat currentChat) {
        CompletableFuture.runAsync(() -> {
            try {
                String encodedMessage = URLEncoder.encode(message, StandardCharsets.UTF_8);
                String url = String.format("%s?prompt=%s&chatId=%s", BASE_URL, encodedMessage,currentChat.getId());
                
                HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json")
                    .GET()
                    .timeout(Duration.ofMinutes(2))
                    .build();
                
                StringBuilder responseBuilder = new StringBuilder();
                client.send(request, HttpResponse.BodyHandlers.ofLines())
                    .body()
                    .forEach(line -> {
                        try {
//                            JsonNode jsonNode = mapper.readTree(line);
                            String chunk = line;
                            
//                            if (jsonNode.has("data")) {
//                                chunk = jsonNode.get("data").asText();
//                            } else if (jsonNode.has("message")) {
//                                chunk = jsonNode.get("message").asText();
//                            }

                            if (chunk != null && !chunk.isEmpty()) {
                                responseBuilder.append(chunk);
                                onChunk.accept(chunk);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                
                onComplete.run();
            } catch (Exception e) {
                e.printStackTrace();
                onChunk.accept("发送消息失败: " + e.getMessage());
                onComplete.run();
            }
        });
    }
} 